package com.ttn.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ttn.auth.mapper.SysUserMapper;
import com.ttn.auth.service.SysMenuService;
import com.ttn.auth.service.SysRoleService;
import com.ttn.auth.service.SysUserService;
import com.ttn.common.core.entity.Result;
import com.ttn.common.core.entity.auth.SysMenu;
import com.ttn.common.core.entity.auth.SysRole;
import com.ttn.common.core.entity.auth.SysUser;
import com.ttn.common.core.entity.auth.vo.SysUserDetailsVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysRoleService sysRoleService;

    @Override
    public Result querySysUserDetails(int sysUserId) {
        SysUserDetailsVO sysUserDetailsVO = new SysUserDetailsVO();
        SysUser sysUser = this.getById(sysUserId);
        if (Objects.nonNull(sysUser)) {
            sysUserDetailsVO.setSysUser(sysUser);
            if (StrUtil.isNotBlank(sysUser.getRoleIds())) {
                LambdaQueryWrapper<SysRole> sysRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                sysRoleLambdaQueryWrapper.in(SysRole::getId, Arrays.asList(sysUser.getRoleIds().split(",")));
                sysUserDetailsVO.setSysRoleList(sysRoleService.list(sysRoleLambdaQueryWrapper));
                if (sysUserDetailsVO.getSysRoleList().size() > 0) {
                    LambdaQueryWrapper<SysMenu> sysMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    List<String> menuIds = Lists.newArrayList();
                    sysUserDetailsVO.getSysRoleList().stream().forEach(sysRole -> {
                        menuIds.addAll(Arrays.asList(sysRole.getMenus().split(",")));
                    });
                    if (menuIds.size() > 0) {
                        sysMenuLambdaQueryWrapper.in(SysMenu::getId, menuIds);
                        sysUserDetailsVO.setSysMenuList(sysMenuService.list(sysMenuLambdaQueryWrapper));
                    }

                }
            }

        }

        return Result.success(sysUserDetailsVO);
    }
}
